<template>
	<view class="custom-page">
		<hs-status-bar></hs-status-bar>
		<top-bar :haveBack="true"></top-bar>
		<scroll-view scroll-y="true" class="custom-scroll">
			<image class="share" src="@/static/images/icon/weixin.png" mode="aspectFit"></image>
			<button class="share btn" @click="share">
			</button>
			<hs-selectPhoneModelPrivate :disabled="true" :phoneModelId="phoneModelId" @selectModel="selectModel"
				style="display: inline-block;position:absolute;top: 17rpx;left: 17rpx;z-index: 1;"
				ref="selectPhoneModel"></hs-selectPhoneModelPrivate>
			<swiper :indicator-dots="true" :duration="1000" class="swiper"
				:class="[userInfo.printerId != 0 && userInfo.printerId != null ? 'swiper-printer' : 'swiper-noprinter']"
				@change="onSwiperChange">
				<swiper-item>
					<view class="image-view" @click="previewImage(0)">
						<!-- 顶层机壳 -->
						<image class="picture btm" :src="baseImageUrl"></image>
						<!-- 贴纸 -->
						<image class="picture" :src="item.imageUrl" v-for="(item, index) of detailInfo.stickerImageList"
							:key="index" :style="{
								height: item.height * 0.75 + 'rpx',
								width: item.width * 0.75 + 'rpx',
								transform:
									`translate(${0.75 * item.x}rpx, ${0.75 * item.y}rpx)`
									+ ` rotate(${item.rotationAngle}deg)`
									+ ` scale(${item.overturn ? -1 * item.scaleX : item.scaleX},${item.scaleY})`,
								zIndex: item.index
							}"></image>
						<!-- 顶层机壳 -->
						<image class="picture top" :src="frameImageUrl"></image>
					</view>
				</swiper-item>
				<swiper-item v-for="(item, index) of skuList[activeSkuIndex].carouselImages" :key="item.id"
					@click="previewImage(index + 1)">
					<view class="image-view">
						<image class="picture" :src="item.imageUrl" mode="aspectFit"></image>
					</view>
				</swiper-item>
			</swiper>
			<view class="sku-box  hs-full-x">
				<view class="to-edit" @click="toEdit">
					去设计
				</view>
				<view class="phone-model">
					<text class="title">机型：</text>
					<view class="select">
						<!-- <hs-selectPhoneModelPrivate :phoneModelId="phoneModelId"
							style="display: inline-block;position:relative;" @selectModel="selectModel"><text
								class="text1">▼</text></hs-selectPhoneModelPrivate> -->

						<hs-selectmachine :phoneModelId="phoneModelId" :isPrivate="true"
							@selectModel="selectModel"><text class="text1">▼</text></hs-selectmachine>

					</view>

				</view>
				<view class="skus">
					<text class="title">材质：</text>
					<view class="select">
						<view class="skus-item" v-for="(item, index) of skuList" :key="item.id"
							@click="chooseSku(item, index)" :class="{ active: activeSkuId == item.id }">
							{{ item.shortName + ' ￥' + item.price / 100 }}
						</view>
					</view>
				</view>
			</view>
			<view class="details">
				<view class="details-item" v-for="(item, index) of skuList[activeSkuIndex].detailImages" :key="index">
					<image class="picture" :src="item.imageUrl" mode="aspectFit"></image>
				</view>
			</view>
		</scroll-view>
		<view class="custom-bottom">
			<!-- <view class="custom retry" @click="$u.debounce(retry)">
				重新生成人像
			</view> -->
			<view class="price">
				￥{{ skuList[activeSkuIndex].price / 100 }}
			</view>

			<!-- <view class="custom" v-if="isStore!=''" @click="toPrint()">  （废弃）
				现场打印
			</view> -->
			<view class="custom" v-if="isStore != '' || abroad || merchant" @click="showModalFn">
				现场打印
			</view>
			<view v-else class="custom" :class="{ retry: isStore != '' }">

				<button open-type="getPhoneNumber" @getphonenumber.stop="getPhoneNumber" v-if="!phoneNumber"
					class="get-phone">授权并获取手机号</button>
				<view class="" @click="$u.debounce(toBuy)">
					立即购买
				</view>

			</view>
		</view>

		<view class="pay-code-box">
			<u-popup :show="payCodeShow" mode="center" :round="17" @close="payCodeShow = false" closeable
				closeOnClickOverlay safeAreaInsetTop>
				<view class="pay-code">
					<view class="pay-code-title">
						<text>请扫描二维码进行支付</text>
					</view>
					<!-- <image class="pay-code-image" :src="payCodeUrl" mode="aspectFit"></image> -->
					<canvas id="qrcode" canvas-id="qrcode" style="width: 180px;height: 180px;"></canvas>
					<view class="">
						<!-- <text>已支付</text> -->
					</view>
				</view>
			</u-popup>
			<u-modal :closeOnClickOverlay="true" @cancel="cancelPayCode" :showCancelButton="true" :show="showModal"
				:title="modalTitle" :content='modalContent' @confirm="shouPayCode"></u-modal>
		</view>

		<preview-phonecase :stickerImageList="detailInfo.stickerImageList" :frameImageUrl="frameImageUrl"
			:baseImageUrl="baseImageUrl" :detail="skuList[activeSkuIndex].carouselImages"
			ref="previewPhonecase"></preview-phonecase>
		<!--<share ref="shareBox" :posterImage="detailInfo.imageUrl" type="0" :sourceId="detailInfo.id"
			:price="skuList[activeSkuIndex].price / 100"></share> -->
		<share ref="shareBox" :posterImage="currentCarouselImage" type="3" :sourceId="detailInfo.id"
			:price="skuList[activeSkuIndex].price / 100"></share>
		<to-print ref="printBox"></to-print>
	</view>
</template>

<script>
import UQRCode from 'uqrcodejs';
import {
	getCustomDetail,
	generateShare,
	getSkuList,
	getInfo,
	checkout
} from '@/api/custom.js'
import {
	getCreditList
} from '@/api/my.js'
import { createOrder } from '@/api/product.js'
import {
	mapGetters,
	mapMutations
} from 'vuex'
import {
	decryptPhoneNumber,
	setDefaultPhoneModel
} from '@/api/user.js';
export default {
	data() {
		return {
			currentSwiperIndex: 0, // 新增当前轮播图索引
			currentCarouselImage: '', // 新增当前轮播图URL
			showModal: false,
			modalTitle: '提示',
			modalContent: '',
			payCodeShow: false,
			detailInfo: {},
			phoneModelId: null,
			// 机壳列表
			skuList: [],
			activeSkuId: null,
			activeSkuIndex: null,
			frameImageUrl: '',
			baseImageUrl: '',
			activeMaterialMap: {},
			reflash: true,
			abroad: false,
			merchant: false,
			phoneModelName: '',
			payCodeUrl: ''
		}
	},
	computed: {
		...mapGetters(['phoneNumber', 'totalCredits', 'isStore', 'getCurrentMaterial', 'userInfo']),
	},
	methods: {
		...mapMutations(['setPhoneNumber', 'setTotalCredits', 'setCurrentMaterial']),
		// 轮播图切换回调
		onSwiperChange(e) {

			this.currentSwiperIndex = e.detail.current
			console.log('onSwiperChange', this.currentSwiperIndex);
			// 计算实际图片索引（首项是商品主图）
			const actualIndex = Math.max(e.detail.current - 1, 0)
			console.log('onSwiperChange', this.currentSwiperIndex);
			this.currentCarouselImage =
				e.detail.current === 0 ?
					this.detailInfo.imageUrl :
					this.skuList[this.activeSkuIndex]?.carouselImages?.[actualIndex]?.imageUrl || ''
			console.log('currentCarouselImage', this.currentCarouselImage);
		},
		// 获取详情
		getCustomDetail() {
			getCustomDetail({
				id: this.detailInfo.id
			}).then(res => {
				this.detailInfo = res.data
				this.activeSkuId = this.detailInfo.skuId
				this.phoneModelId = this.detailInfo.materialMap[11]
				this.getSkuList(this.detailInfo.materialMap[11], true)
			})
		},
		// 去编辑
		toEdit() {
			// uni.navigateTo({
			// 	url: `/pages/diy/diyPhoneCase?id=${this.detailInfo.id}`
			// })
			const currentMaterial = this.getCurrentMaterial || this.skuList[this.activeSkuIndex]
			uni.navigateTo({
				url: `/pages/diy/diyPhoneCase?id=${this.detailInfo.id}&material=${JSON.stringify(currentMaterial)}`
			})
		},
		// 放大图片预览
		async previewImage(index) {
			console.log('previewImage', index);
			const allImages = [
				this.detailInfo.imageUrl, // 第一张详情图
				...this.skuList[this.activeSkuIndex]?.carouselImages?.map(i => i.imageUrl) || []
			];
			// 安全索引处理
			const safeIndex = Math.min(index, allImages.length - 1);
			uni.previewImage({
				current: safeIndex,
				urls: allImages
			});
			// this.$refs.previewPhonecase.show(index)
			// this.reflash = false

			// let arr = [this.detailInfo.imageUrl]
			// uni.previewImage({
			// 	current: 0,
			// 	urls: arr
			// });
		},
		// 选择手机型号
		selectModel(data) {
			this.phoneModelId = data
			uni.$u.debounce(() => {
				this.getSkuList(this.phoneModelId)
			})
		},
		// 获取机壳列表
		getSkuList(phoneModelId, isInit) {
			getSkuList({
				materialMap: {
					11: phoneModelId
				},
				materialSubType: this.detailInfo.materialSubType,
				pageSize: 50
			}).then(res => {
				this.skuList = res.data
				console.log('isInit', isInit);
				if (isInit) {
					this.activeSkuIndex = this.skuList.findIndex(item => {
						return item.id == this.detailInfo.skuId
					})
					this.chooseSku(this.skuList[this.activeSkuIndex], this.activeSkuIndex)
				} else {
					let idx = this.skuList.findIndex(item => {
						return this.activeMaterialMap[10] == item.materialMap[10]
					})
					console.log(this.detailInfo.materialMap[10]);
					idx = idx == -1 ? 0 : idx
					console.log('idx', this.skuList[idx]);
					this.chooseSku(this.skuList[idx], idx)
				}

			})
			setDefaultPhoneModel({
				phoneModelId: phoneModelId
			}).then(res => {
				console.log('setDefaultPhoneModel', res);
				this.phoneModelName = res.data.phoneModelName
			})
		},
		// 选择机壳
		chooseSku(data, index) {
			this.activeSkuId = data.id
			this.activeSkuIndex = index
			this.activeMaterialMap = data.materialMap
			this.frameImageUrl = data.frameImageUrl
			this.baseImageUrl = data.baseImageUrl
			this.$store.commit('setPhoneModelId', this.phoneModelId)
			this.$store.commit('setCurrentMaterial', data)
		},
		// 去购买
		async toBuy() {
			let orderData = [{
				customProductId: this.detailInfo.id,
				quantity: 1
			}]
			uni.setStorageSync('orderData', orderData)
			uni.navigateTo({
				url: '/pages/order/order'
			})
		},
		async showModalFn() {
			if (this.abroad) {
				console.log('this.skuList', this.skuList[this.activeSkuIndex].name);
				this.modalContent = `机型：${this.phoneModelName}，材质：${this.skuList[this.activeSkuIndex].name}，确认打印吗？`
				this.showModal = true
				return
			}
			if (!this.abroad || this.merchant) {
				await this.createcheckoutFn()
				this.showModal = false
				this.payCodeShow = true
			} else {
				this.showModal = true
			}
		},
		async createcheckoutFn() {
			try {
				let obj = {
					customProductList: [{
						customProductId: this.detailInfo.id,
						quantity: 1
					}]
				}
				console.log({ ...obj });
				const res = await checkout(obj)
				const printerId = this.userInfo.printerId
				const resp = await createOrder({
					...obj,
					printerId
				})
				this.formatWXPayToQRCode(resp.data.payUrl)
				// this.payCodeUrl = resp.data.payUrl
			} catch (err) {
				console.log('err', err);
				uni.showToast({ title: 'error', icon: 'error' })
			}
		},
		async shouPayCode() {

			if (!this.abroad) {
				// 国内商家操作
				this.showModal = false
				this.payCodeShow = true
			} else {
				// 国外商家操作
				await this.createcheckoutFn()
				uni.showToast({ title: 'success', icon: 'success' })

				this.showModal = false
			}
		},
		formatWXPayToQRCode(url) {
			// 获取uQRCode实例
			var qr = new UQRCode();
			// 设置二维码内容
			qr.data = url;
			// 设置二维码大小，必须与canvas设置的宽高一致
			qr.size = 180;
			// 调用制作二维码方法
			qr.make();
			// 获取canvas上下文
			var canvasContext = uni.createCanvasContext('qrcode');
			// 设置uQRCode实例的canvas上下文
			qr.canvasContext = canvasContext;
			// 调用绘制方法将二维码图案绘制到canvas上
			qr.drawCanvas();
		},
		cancelPayCode() {
			this.payCodeShow = false
			this.showModal = false
		},
		// 重新定制
		retry() { },
		async share() {
			this.$refs.shareBox.open()
		},

		// 获取手机号授权
		getPhoneNumber(e) {
			if (e.detail.code) {
				decryptPhoneNumber({
					code: e.detail.code,
				}).then(response => {
					this.setPhoneNumber(response.data)
					this.toBuy()
				})
			}
		},
		// 以前的打印（废弃）
		toPrint() {
			if (!this.detailInfo.printable) return uni.$u.toast('抱歉，此机型暂时不能打印，请切换其它机型或材质试试');
			let sukData = {
				phoneModel: this.$refs.selectPhoneModel.model.name,
				material: this.skuList[this.activeSkuIndex].name,
				id: this.detailInfo.id,
				address: this.isStore.split(':')[0],
				port: this.isStore.split(':')[1]
			}
			this.$refs.printBox.init(sukData)
		}
	},
	async onShareAppMessage() {
		const {
			data
		} = await generateShare({
			type: 1,
			sourceType: 0,
			sourceId: this.detailInfo.id
		})
		this.$refs.shareBox.close()
		const imageUrl = await this.$refs.shareBox.drawCanvas1()
		return {
			title: '我定制了一个手机壳，快来看看吧',
			// imageUrl: this.detailInfo.imageUrl,
			imageUrl: imageUrl,
			path: `/pages/product/productDetail?scene=${data.id}`,
			success: () => {

			}
		}
	},
	onLoad(e) {
		this.detailInfo.id = e.id
		const that = this
		uni.$on('payCustomViewStatus', function (msg) {
			that.payCodeShow = false
		})
	},
	onShow() {
		if (!this.reflash) {
			this.reflash = true
		} else {
			this.getCustomDetail()
		}

		getInfo().then(res => {
			this.abroad = res.data.abroad
			this.merchant = res.data.merchant
		})

	},
	onUnload() {
		console.log('B页面的onUnload')
		uni.$emit('pageReturn', { from: 'customView' })
	}
}
</script>

<style lang="scss">
//轮播图选择器位置样式调整
/deep/ .wx-swiper-dots {
	position: absolute;
	bottom: 50rpx !important;
	// left: 10% !important;
}

/deep/ .wx-swiper-dots-horizontal {
	// left: 10% !important;
}

.custom-page {
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;

	.header {
		height: 56rpx;
		line-height: 56rpx;

		.back {
			height: 25rpx;
			width: 25rpx;
			transform: rotate(180deg);
			padding: 16rpx 25rpx;
		}

		.share {
			height: 56rpx;
			width: 56rpx;
			float: right;
			margin-right: 25rpx;
		}
	}

	.custom-scroll {
		flex: 1;
		overflow: hidden;

		.share {
			height: 56rpx;
			width: 56rpx;
			position: absolute;
			right: 25rpx;
			top: 25rpx;
			z-index: 1;
			border: none;
			border-radius: 50%;

			&.btn {
				height: 110rpx;
				width: 110rpx;
				right: 5rpx;
				top: 5rpx;
				opacity: 0;
			}
		}

		.swiper {
			// height: 900rpx;
			background-color: #fff;
			// height: 1000rpx;
		}

		.swiper-printer {
			height: 810rpx;
		}

		.swiper-noprinter {
			height: 1000rpx;
		}

		.image-view {
			height: 750rpx;
			position: relative;
			overflow: hidden;
			transform: scale(1.05) translate3d(0, 0, 0) translate(0, 50rpx);
			background: #fff;
			-webkit-backface-visibility: hidden;
			-webkit-transform: scale(1.05) translate3d(0, 0, 0) translate(0, 50rpx);
			-webkit-mask-image: -webkit-radial-gradient(white, black);

			.picture {
				height: 100%;
				width: 100%;
				position: absolute;
				top: 0;
				left: 0;

				&.top,
				&.btm,
				&.bg,
				&.fg {
					height: 750rpx;
					width: 750rpx;
				}

				&.btm {
					z-index: 0;
				}

				&.bg {
					z-index: 2;
				}

				&.fg {
					z-index: 4;
				}

				&.top {
					z-index: 999;
				}

			}

			.custom-view-image {
				height: 750rpx;
				width: 750rpx;
				position: absolute;
				top: 0;
				left: 0;
			}
		}


		.sku-box {
			// height: 380rpx;
			position: relative;
			// margin: 180rpx 0 30rpx;

			.bg-scroll {
				width: calc(100% - 136rpx);
				height: 210rpx;
				margin: 0 auto;

				.bg-list {
					display: flex;
					justify-content: left;
					height: 100%;

					.bg-item {
						width: 130rpx;
						height: 100%;
						margin-right: 28rpx;
						flex-shrink: 0;

						.picture {
							height: 100%;
							width: 100%;
							box-sizing: border-box;
							margin-bottom: 28rpx;
							flex-shrink: 0;
							border-radius: 17rpx;

							&.active {
								border: 5rpx solid #333;
							}
						}

						.price {
							font-size: 38.55rpx;
							font-weight: 500;
							color: #3D3D3D;
							text-align: center;
						}
					}
				}
			}

			.skus {
				display: flex;
				margin-top: 17rpx;
				justify-content: start;

				.title {
					color: #979797;
					font-size: 28rpx;
					margin-left: 35rpx;
					line-height: 50rpx;
					white-space: nowrap;
				}

				.select {
					display: flex;
					justify-content: start;
					flex-wrap: wrap;
					flex-grow: 0;
					flex-direction: column;

					.skus-item {
						height: 50rpx;
						border-radius: 30rpx;
						border: 2rpx solid transparent;
						line-height: 50rpx;
						text-align: center;
						font-size: 26rpx;
						font-weight: bold;
						flex-wrap: wrap;
						justify-content: start;
						flex-shrink: 0;
						padding: 0 17rpx;
						margin: 6rpx 0 0;

						&.active {
							border: 2rpx solid #333;
						}
					}
				}

			}

			.phone-model {
				height: 50rpx;
				line-height: 50rpx;
				font-size: 28rpx;
				margin: 26rpx 35rpx 0;
				position: relative;
				color: #979797;

				.select {
					display: inline-block;
					border-radius: 50rpx;
					border: 2rpx solid #333;
					padding: 0 17rpx;
					font-size: 26rpx;
					height: 50rpx;

					text {
						font-weight: bold;
						color: #333;
					}

					.text1 {
						margin-left: 17rpx;
						font-size: 20rpx;
					}
				}

			}

			.left {
				position: absolute;
				height: 42rpx;
				width: 42rpx;
				top: 94rpx;
				left: 26rpx;
				transform: rotate(180deg);

				.icon {
					height: 100%;
					width: 100%;
				}
			}

			.right {
				position: absolute;
				height: 42rpx;
				width: 42rpx;
				top: 94rpx;
				right: 26rpx;

				.icon {
					height: 100%;
					width: 100%;
				}
			}

			.to-edit {
				width: 143rpx;
				height: 75rpx;
				border-radius: 78rpx;
				font-size: 35rpx;
				box-sizing: border-box;
				border: 2rpx solid #333333;
				text-align: center;
				line-height: 71rpx;
				background-color: #333;
				color: #fff;
				position: absolute;
				top: -130rpx;
				right: 17rpx;
			}

			.right-bar {
				position: absolute;
				left: 17rpx;
				top: -217rpx;
				background: #fff;
				border-radius: 17rpx;
				box-shadow: 0rpx 0rpx 6rpx 0rpx #ccc;
				display: flex;
				flex-direction: column;

				image {
					width: 84rpx;
					height: 50rpx;
					padding: 10rpx 10rpx 30rpx;
					position: relative;
					border-radius: 17rpx;

					&.active {
						background-color: #f3f3f3;
					}

					&:nth-child(1) {
						border-radius: 17rpx 17rpx 0 0;
						border-bottom: 1rpx solid #e2e2e2;

						&::after {
							content: '背景';
							font-size: 22rpx;
							position: absolute;
							bottom: 0;
							left: 50%;
							transform: translate(-50%);
							color: #515151;
						}
					}

					&:nth-child(2) {
						border-radius: 0 0 17rpx 17rpx;

						&::after {
							content: '人像';
							font-size: 22rpx;
							position: absolute;
							bottom: 0;
							left: 50%;
							transform: translate(-50%);
							color: #515151;
						}
					}

					&:nth-child(3) {
						position: absolute;
						top: -107rpx;
						background: #fff;
						border-radius: 17rpx;
						box-shadow: 0rpx 0rpx 6rpx 0rpx #ccc;

						&::after {
							content: '原图';
							font-size: 22rpx;
							position: absolute;
							bottom: 0;
							left: 50%;
							transform: translate(-50%);
							color: #515151;
						}
					}
				}
			}

		}

		.details {
			margin-top: 60rpx;

			.details-item {
				height: 750rpx;
				width: 750rpx;

				image {
					height: 100%;
					width: 100%;
				}
			}
		}
	}

	.custom-bottom {
		display: flex;
		height: 100rpx;
		justify-content: space-between;
		margin: 20rpx 0 0 0;
		padding: 0 47rpx;

		.custom {
			width: 250rpx;
			height: 78.8rpx;
			border-radius: 78rpx;
			font-size: 35rpx;
			box-sizing: border-box;
			text-align: center;
			line-height: 78.8rpx;
			background-color: #333;
			color: #fff;
		}

		.get-phone {
			height: 78rpx;
			opacity: 0;
			position: absolute;
			width: 250rpx;
		}

		.custom.retry {
			border: 2rpx solid #333;
			background-color: #fff;
			color: #333;
		}

		.price {
			font-size: 35rpx;
			height: 78.8rpx;
			line-height: 78.8rpx;
			font-weight: bold;
		}
	}

	.pay-code-box {
		.pay-code {
			width: 500rpx;
			height: 500rpx;
			background-color: #fff;
			border-radius: 17rpx;
			display: flex;
			flex-direction: column;
			padding: 0 20rpx;
			justify-content: space-between;
			align-items: center;

			.pay-code-title {
				font-size: 35rpx;
				font-weight: bold;
				text-align: center;
				margin-top: 30rpx;
			}

			.pay-code-image {
				width: 200rpx;
				height: 200rpx;
				margin: 0 auto;
				margin-top: 30rpx;
			}

			.pay-code-text {
				font-size: 35rpx;
				font-weight: bold;
				text-align: center;
				margin-top: 30rpx;
				background-color: #00B26A;
				color: #fff;
				border-radius: 17rpx;
				padding: 10rpx 20rpx;
			}
		}
	}

}
</style>